package com.doupi.partner.dal.plugin;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.Properties;

/**
 * 查询拦截器，动态修改查询条件
 * 
 * @author Alvin Wang
 * @version 1.0.0 @ 2017-04-20
 */
@Intercepts(@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }))
public class PageInterceptor implements Interceptor {
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
		MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
		if (statementHandler instanceof Proxy) {
			statementHandler = (StatementHandler) metaObject.getValue("h.target");
			metaObject = SystemMetaObject.forObject(statementHandler);
		}
		RowBounds rowBounds = (RowBounds) metaObject.getValue("delegate.rowBounds");
		if (null != rowBounds) {
			if (rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT) {
				BoundSql boundSql = statementHandler.getBoundSql();
				metaObject.setValue("delegate.boundSql.sql", boundSql.getSql() + " limit " + rowBounds.getOffset() + " , " + rowBounds.getLimit());
			}
			metaObject.setValue("delegate.rowBounds.offset", 0);
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {

	}
}
